package com.elysia.service;

import com.elysia.mapper.UserMapper;
import com.elysia.pojo.User;
import com.elysia.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    //1.使用工具类获取SqlSessionFactory
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 登陆方法
     * @param username
     * @param password
     * @return
     */
    public User login(String username,String password){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4.调用方法
        User user = mapper.select(username, password);
        //释放资源
        sqlSession.close();
        //最后再返回一个user对象
        return user;
    }
    public Boolean register(User user){
        //1.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //3.调用方法
        User u = mapper.selectByUsername(user.getUsername());

        //4.判断用户名是否存在
        if (u == null){
            //用户名不存在的话，就能注册
            mapper.add(user);
            sqlSession.commit();
        }
        sqlSession.close();
        return u == null;
    }
}
